#include "StompedReality/Asset/JointAnimationPlayer.h"
#include <iostream>
namespace StompedReality
{
namespace animation
{
JointAnimationPlayer::JointAnimationPlayer( )
{
  this->_currentFrame = 0;
  this->_currentFrameIDX = 0;
  this->_frameTime = 0;
  this->_nextFrame = 0;
  this->_nextFrameIDX = 0;
  this->_playing = 0;
  this->_startIndex = 0;
  this->_startTime = 0;
  this->_animation = 0;
  this->_playAsLoop = false;
}

JointAnimationPlayer::~JointAnimationPlayer( )
{
}

void JointAnimationPlayer::setAnimation( JointAnimation* animation )
{
  this->_animation = animation;
}

void JointAnimationPlayer::playAsLoop( bool looped )
{
  this->_playAsLoop = looped;
}

bool JointAnimationPlayer::shoudlPlayAsLoop( )
{
  return this->_playAsLoop;
}

double JointAnimationPlayer::getFrameTime( )
{
  return this->_frameTime;
}

int JointAnimationPlayer::getCurrentIndex( )
{
  return this->_currentFrameIDX;
}

int JointAnimationPlayer::getNextIndex( )
{
  return this->_nextFrameIDX;
}

KeyFrame* JointAnimationPlayer::getCurrentFrame( )
{
  return this->_currentFrame;
}

KeyFrame* JointAnimationPlayer::getNextFrame( )
{
  return this->_nextFrame;
}

bool JointAnimationPlayer::isPlaying( )
{
  return this->_playing;
}

void JointAnimationPlayer::start ( )
{
  this->_currentFrameIDX = this->_startIndex;
  this->_nextFrameIDX = (this->_startIndex + 1) % this->_animation->numberOfFrames( );
  this->_currentFrame = this->_animation->getKeyFrame ( this->_currentFrameIDX );
  this->_nextFrame = this->_animation->getKeyFrame ( this->_nextFrameIDX );
  this->_frameTime = this->_startTime;
  this->_playing = true;
}

void JointAnimationPlayer::updateFrameTime ( double dt )
{
  this->_frameTime += dt;

  // the frame played its full duration
  if ( this->_frameTime >= this->_currentFrame->getDuration( ) )
  {
    // update frame time to next frame;
    this->_frameTime -= this->_currentFrame->getDuration( );

    // update current frame index
    ++this->_currentFrameIDX %= this->_animation->numberOfFrames( );
    ++this->_nextFrameIDX %= this->_animation->numberOfFrames( );

    // back at the first frame and not loop => stop playing
    if ( this->_currentFrameIDX == 0 && !this->shoudlPlayAsLoop( ) )
    {
      this->_playing = false;
    }
    else
    {
      this->_currentFrame = this->_nextFrame;
      this->_nextFrame = this->_animation->getKeyFrame ( this->_nextFrameIDX );
    }
  }
}

float JointAnimationPlayer::calculateRotation( )
{
  return (float) ( this->getCurrentFrame( )->GetRotation( ) +
                   ( this->_frameTime / this->getCurrentFrame( )->getDuration( ) ) *
                   ( this->getNextFrame( )->GetRotation( ) - this->getCurrentFrame( )->GetRotation( ) ) );
}

}
}
